import { useEffect, useState } from 'react';
import { useRoutes, useLocation, useNavigate } from 'react-router-dom';
import router from '@/router';
import { useRecoilValue } from 'recoil';
import { userSelector } from '@/store/user';
import Loading from '@/components/Loading';
interface RedirectProps {
    path: string;
    replace?: boolean;
    state?: any;
}
export const BeforeRouterEnter = () => {
    const outlet = useRoutes(router);
    const userInfo = useRecoilValue(userSelector);
    const location = useLocation();
    // const [isLoading, setIsLoading] = useState(true);

    // useEffect(() => {
    //     setIsLoading(false);
    // }, []);

    // if (isLoading) {
    //     return <Loading fullScreen />;
    // }
    // 白名单路由
    const whiteList = ['/', '/login', '/register', '/forgot-password'];

    if (userInfo.token && ['/', '/login'].includes(location.pathname)) {
        return <Redirect path="/app/index" replace />;
    }

    // 未登录且访问非白名单路由
    if (!userInfo.token && !whiteList.includes(location.pathname)) {
        return <Redirect path="/login" replace state={{ from: location.pathname }} />;
    }

    return outlet;
};

const Redirect: React.FC<RedirectProps> = ({ path, replace = true, state }) => {
    const navigate = useNavigate();
    useEffect(() => {
        navigate(path, { replace, state });
    }, [path, replace, state, navigate]);

    return <Loading fullScreen />;
};
